<script setup lang="ts">
import { ref } from "vue";
import { LCircle, LMarker } from "@vue-leaflet/vue-leaflet";
import { useMapStore } from "@/store";
import { MAP_ACTION } from "@/views/pipe-network/constants";
import {
  deletePoint,
  queryPointsPro,
  queryPolylinesPro,
  updatePoint,
  movePoint,
} from "@/api/pipe";
import { useLocalStore } from "@/views/pipe-network/store";
import { getAddressByLonLat } from "@/utils/map";
const { L }: any = window;
const props = defineProps({
  deviceCategoryManager: Object,
});
const pointListRef = ref([]);
const polylineListRef = ref([]);
const dialogVisible = ref<boolean | number>(false);
const mapStore = useMapStore();
const { mapAction } = storeToRefs(mapStore);
const localStore = useLocalStore();
const { updatePointAPICount } = storeToRefs(localStore);
const onClick = (e: any) => {
  const isConnectionTwoPointsAction =
    mapAction.value === MAP_ACTION.CONNECTION_POINT_TWO;
  const isModifyInfoAction = mapAction.value === MAP_ACTION.EDIT;
  const { pointId } = e.target.options.attribution;
  const obj = pointListRef.value.find((item: any) => item.pointId === pointId);
  if (isConnectionTwoPointsAction) {
    const { depth } = e.target.options.attribution;
    const value = !depth ? 0 : Number(depth);
    mapStore.addSelectedMarkers({ latlng: e.latlng, depth: value });
  }
  if (isModifyInfoAction) {
    if (obj) {
      mapStore.setEditingPipePoint(obj);
    }
  }
  if (!mapAction.value && obj) {
    localStore.setSelectedFeature(obj);
  }
};
const onDragend = async (e: any) => {
  const { lat, lng } = e.target.getLatLng();
  const { pointId } = e.target.options.attribution;
  const obj: any = pointListRef.value.find(
    (item: any) => item.pointId === pointId
  );
  if (obj) {
    const jsonPoint = JSON.stringify({
      type: "Point",
      coordinates: [lng, lat],
    });
    obj.jsonPoint = jsonPoint;
    const res: any = await getAddressByLonLat(lng, lat);
    if (res.status === "1") {
      const {
        regeocode: { formatted_address },
      } = res;
      obj.address = formatted_address;
    }

    delete obj.latlng;
    delete obj.icon;
    delete obj.jsonGeom;
  }
  // 移动管点 参数
  const params = {
    pointId: obj.pointId,
    position: JSON.stringify([lng, lat]),
    address: obj.address,
    jsonPoint: JSON.stringify([lng, lat]),
  };
  movePoint(params).then(({ succeeded }: any) => {
    if (succeeded) {
      getAllPoints();
      ElMessage({
        message: "修改成功",
        type: "success",
      });
    }
  });
};
const getIcon = (classId: string) => {
  const iconUrl = props.deviceCategoryManager.getIconUrl(classId);
  return iconUrl
    ? L.icon({
        iconUrl,
        iconSize: [32, 32],
        iconAnchor: [16, 27],
      })
    : null;
};
const getAllPoints = () =>
  queryPointsPro({ pageSize: 100000, pageIndex: 1 }).then(
    ({ data, errors, succeeded }: any) => {
      if (succeeded && Array.isArray(data?.items)) {
        pointListRef.value = data.items
          .filter((item: any) => item.jsonGeom)
          .map((item: any) => {
            const [lng, lat] = JSON.parse(item.jsonGeom).coordinates;
            return {
              ...item,
              latlng: [lat, lng],
              icon: getIcon(item.classId),
            };
          });
      }
    }
  );
const getAllLines = () =>
  queryPolylinesPro({ pageSize: 100000, pageIndex: 1 }).then(
    ({ data, errors, succeeded }: any) => {
      if (succeeded && Array.isArray(data?.items)) {
        polylineListRef.value = data.items
          .filter((item: any) => item.jsonGeom)
          .map((item: any) => {
            const { coordinates } = JSON.parse(item.jsonGeom);
            const [lng, lat] = coordinates[0];
            const [endLng, endLat] = coordinates[coordinates.length - 1];
            return {
              ...item,
              startPoint: [lat, lng],
              endPoint: [endLat, endLng],
            };
          });
      }
    }
  );
const _deletePoint = (pointId: number) => {
  deletePoint(pointId).then((res: any) => {
    if (res.succeeded) {
      ElMessage("删除成功！");
      getAllPoints();
    } else {
      ElMessage("删除失败！");
    }
  });
};
onMounted(() => {
  getAllPoints();
  getAllLines();
});
watchEffect(() => {
  if (updatePointAPICount.value > -1) {
    getAllPoints();
  }
});
</script>

<template v-if="positionRef">
  <LMarker
    :key="pointId + mapAction + latlng.join('-')"
    v-for="{ latlng, pointId, icon, depth } in pointListRef"
    :lat-lng="latlng"
    :icon="icon"
    @click="onClick"
    @dragend="onDragend"
    :attribution="{ pointId, depth }"
    :draggable="mapAction === MAP_ACTION.MOVE"
  />
  <template v-if="mapAction === MAP_ACTION.DELETE">
    <LMarker
      v-for="{ latlng, pointId } in pointListRef"
      :key="pointId"
      :lat-lng="latlng"
      :icon="
        L.divIcon({
          html: `<div style=&quot;width: 13px;height: 13px;cursor: pointer; position: relative; top: -37px; left: 17px; border: 1px solid;transform:scale(1.1);&quot;>
                    <svg viewBox=&quot;0 0 40 40&quot; style=&quot;position: relative;left: 0px; top: -4px;&quot;>
                        <path stroke=&quot;#FF0000&quot; stroke-width=&quot;3&quot; d=&quot;M 10,10 L 30,30 M 30,10 L 10,30&quot; />
                  </svg>
                </div>`,
          className: 'abc',
        })
      "
      @click="dialogVisible = pointId"
    />
  </template>
  <template v-if="mapAction === MAP_ACTION.ADD_POINT">
    <LCircle
      v-for="{ startPoint, lineId } in polylineListRef"
      :key="lineId"
      :lat-lng="startPoint"
      :radius="20"
      color="red"
      fill-color="white"
      :fillOpacity="0.3"
      :pacity="0.3"
      @click="(e: any) => mapStore.setAddedPipePoint(e.target.getLatLng())"
      @mouseover="
        (e: any) => {
          e.target.getElement().style.fillOpacity = 1;
          e.target.getElement().style.opacity = 1;
        }
      "
      @mouseout="
        (e: any) => {
          e.target.getElement().style.fillOpacity = 0.3;
          e.target.getElement().style.opacity = 0.3;
        }
      "
    />
    <LCircle
      v-for="{ endPoint, lineId } in polylineListRef"
      :key="lineId"
      :lat-lng="endPoint"
      :radius="20"
      color="red"
      fill-color="white"
      :fillOpacity="0.3"
      :pacity="0.3"
      @click="(e: any) => mapStore.setAddedPipePoint(e.target.getLatLng())"
      @mouseover="
        (e: any) => {
          e.target.getElement().style.fillOpacity = 1;
          e.target.getElement().style.opacity = 1;
        }
      "
      @mouseout="
        (e: any) => {
          e.target.getElement().style.fillOpacity = 0.3;
          e.target.getElement().style.opacity = 0.3;
        }
      "
    />
  </template>
  <el-dialog v-model="dialogVisible" title="提示" width="400">
    <span class="dialog-content">确认删除吗？</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="
            _deletePoint(dialogVisible);
            dialogVisible = false;
          "
        >
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.dialog-content {
  display: inline-block;
  padding: 20px 20px 0;
}

.dialog-footer {
  padding: 20px;
}
</style>
